package password.hb.com.password.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import password.hb.com.password.R;
import password.hb.com.password.entity.APP;

/**
 * Created by A on 2016/12/14.
 */

public class ComponentImage extends View {

    private List<Image> imageList;

    private int cloumns;

    private int mWidth;
    private int mHeight;

    private int imageHeight;//每张图片的高度
    private int imageWidth;//每张图片的宽度

    private boolean isSelected;//是否有图片被选中
    private int selectedIndex;//被选中图片的index

    public static final int NO_IMAGE_SELECTED = -1;//没有选中的selectedIndex

    private int padding = 2;//每张图片的间隔

    private Paint bgPaint;//画背景
    private Paint selectedPaint;//画选中的背景

    private ClickListener clickListener;

    public ComponentImage(Context context) {
        super(context);
    }

    public ComponentImage(Context context, AttributeSet attrs) {
        super(context, attrs);
        imageList = new ArrayList<>();
        isSelected = false;
        selectedIndex = NO_IMAGE_SELECTED;

        bgPaint = new Paint();
        bgPaint.setStyle(Paint.Style.FILL);
        bgPaint.setColor(Color.WHITE);

        selectedPaint = new Paint();
        selectedPaint.setStyle(Paint.Style.FILL);
        selectedPaint.setColor(Color.BLUE);

        initAttrs(attrs);
    }

    public void addImage(APP app){
        Image image = new Image(app);
        this.imageList.add(image);
    }

    public void addImage(List<APP> imageList){
        for(APP app : imageList){
            addImage(app);
        }
    }
    //是否有图片被选中
    public boolean isSelected(){
        return this.isSelected;
    }
    //得到选中图片的index
    public int getSelectedIndex(){
        return this.selectedIndex;
    }

    public void setSelectedImage(int index){
        this.selectedIndex = index;
        this.invalidate();
    }

    public void setSelectedImage(String name){
        int index = -1;
        int size = imageList.size();
        for(int i=0;i<size;i++){
            Image image = imageList.get(i);
            if(image.getApp().getName().equals(name)){
                image.setSelected(true);
                this.isSelected = true;
                index = i;
                break;
            }
        }
        if(index!=-1){
            setSelectedImage(index);
        }
    }

    public APP getSelectedApp(){
        return this.imageList.get(selectedIndex).getApp();
    }

    private void initAttrs(AttributeSet attrs){
        if(attrs!=null){
            TypedArray array = null;
            try{
                array = getContext().obtainStyledAttributes(attrs, R.styleable.ComponentImage);
                this.cloumns = array.getInt(R.styleable.ComponentImage_cloumns,1);

                array.recycle();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for(Image image:imageList){

            if(image.getSelected()) {
                image.drawSelectedImage(canvas);
//                canvas.drawRect(image.getRect(),selectedPaint);
            }else{
//                canvas.drawRect(image.getRect(),bgPaint);
                image.drawOriginImage(canvas);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //获取宽度的模式和大小
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        //获取高度的模式和大小
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        //设置view的宽和高
        this.mWidth = this.measureWidth(widthMode,width);
        this.mHeight = this.measureHeight(heightMode,height);

        this.setMeasuredDimension(mWidth,mHeight);

        this.imageWidth = mWidth/cloumns;
        this.imageHeight = this.imageWidth;

        meaasureImageList();
    }

    //计算每一个image的位置
    private void meaasureImageList(){
        int imageNum = imageList.size();
        for(int i=0;i<imageNum;i++){
            int x=i%cloumns;
            int y=i/cloumns;
            Rect rect = new Rect();
            rect.left = x*imageWidth+padding;
            rect.right = (x+1)*imageWidth-padding;
            rect.top = y*imageHeight+padding;
            rect.bottom = (y+1)*imageHeight-padding;
            imageList.get(i).setRect(rect);

        }

    }

    private int measureWidth(int mode ,int width){
        switch (mode){
            case MeasureSpec.UNSPECIFIED:
                break;
            case MeasureSpec.AT_MOST:
                //根据图片本身的宽度来确定整个View的宽度
                int firstCloum = imageList.size()<cloumns?imageList.size():cloumns;
                int viewWidth = 0;
                for(int i=0;i<firstCloum;i++){
                    viewWidth += imageList.get(i).getDrawable().getIntrinsicWidth();
                }
                this.mWidth = width<viewWidth?width:viewWidth;
                break;
            case MeasureSpec.EXACTLY:
                this.mWidth = width;
                break;
        }
        return mWidth;
    }

    private int measureHeight(int mode , int height){
        switch (mode){
            case MeasureSpec.UNSPECIFIED:
                break;
            case MeasureSpec.AT_MOST:
                //根据宽度确定高度
                if(this.mWidth>0 && imageList.size()>0){
                    int imageWidth = mWidth/this.cloumns;
                    int rows = (imageList.size()-1)/cloumns+1;
                    this.mHeight = imageWidth*rows;
                }
                break;
            case MeasureSpec.EXACTLY:
                this.mHeight = height;
                break;
        }
        return mHeight;
    }

    public void setOnClickListener(ClickListener clickListener){
        this.clickListener = clickListener;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        int indexX = (int)(x/imageWidth);
        int indexY = (int)(y/imageHeight);
        int index = indexX+(indexY*cloumns);

        if(index > (imageList.size()-1)){
            return false;
        }

        if(isSelected){//当前已经有图片被选中
            imageList.get(selectedIndex).setSelected(false);
            imageList.get(index).setSelected(true);
            selectedIndex = index;
        }else{//当前还没有图片被选中
            imageList.get(index).setSelected(true);
            selectedIndex = index;
            isSelected = true;
        }

        if(clickListener!=null){
            clickListener.onClick(getSelectedApp(),selectedIndex);
        }

        this.invalidate();
        return false;
    }

    //图片类
    class Image{
        private Drawable drawable;
        private Rect rect;
        private boolean selected;

        private Paint imgPaint;
        private Drawable selectedDrawable;

        private APP app;

//        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public Image(APP app){
            this.app = app;
            this.drawable=getResources().getDrawable(this.app.getImageId());
            this.selectedDrawable = getResources().getDrawable(R.mipmap.selected);
//            this.drawable = getContext().getDrawable(this.app.getImageId());
//            this.selectedDrawable = getContext().getDrawable(R.mipmap.selected);
            selected = false;

        }

        private void initPaint(){
            imgPaint = new Paint();
            imgPaint.setStyle(Paint.Style.FILL);
            BitmapShader bitmapShader = new BitmapShader(getBitmap(), Shader.TileMode.CLAMP,
                    Shader.TileMode.CLAMP);
            imgPaint.setShader(bitmapShader);
        }

        public void setRect(Rect rect){
            this.rect = rect;
            this.drawable.setBounds(rect);
            Rect selectedRect = new Rect();
            selectedRect.left = rect.left + rect.width()/4;
            selectedRect.right = rect.right - rect.width()/4;
            selectedRect.top = rect.top + rect.height()/4;
            selectedRect.bottom = rect.bottom - rect.height()/4;
            this.selectedDrawable.setBounds(selectedRect);
        }

        public Drawable getDrawable(){
            return this.drawable;
        }

        public void setSelected(boolean selected){
            this.selected = selected;
        }

        public boolean getSelected(){
            return this.selected;
        }

        public Rect getRect(){
            return this.rect;
        }

        public void drawOriginImage(Canvas canvas){
            this.drawable.clearColorFilter();
            this.drawable.draw(canvas);

        }

        public void drawSelectedImage(Canvas canvas){
            this.drawable.clearColorFilter();
            this.drawable.draw(canvas);
            this.selectedDrawable.draw(canvas);
        }

        public void drawCycleImage(Canvas canvas){
            initPaint();
            int x = rect.left + rect.width()/2;
            int y = rect.top + rect.height()/2;
            int radiu = rect.width()<rect.height()?rect.width()/2:rect.height()/2;
            canvas.drawCircle(x,y,radiu,imgPaint);
        }

        public void drawGreyImage(Canvas canvas){
            ColorMatrix matrix = new ColorMatrix();
            matrix.setSaturation(0);
            ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
            this.drawable.setColorFilter(filter);
            this.drawable.draw(canvas);
        }

        public Bitmap getBitmap(){
            int w = drawable.getIntrinsicWidth();
            int h = drawable.getIntrinsicHeight();

            System.out.println("Drawable转Bitmap");
            Bitmap.Config config =
                    drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                            : Bitmap.Config.RGB_565;
            Bitmap bitmap = Bitmap.createBitmap(w,h,config);
            //注意，下面三行代码要用到，否在在View或者surfaceview里的canvas.drawBitmap会看不到图
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, w, h);
            drawable.draw(canvas);
            return bitmap;
        }

        public APP getApp(){
            return this.app;
        }
    }

    //点击事件接口
    public interface ClickListener{
        public void onClick(APP app,int index);
    }
}
